<template>
  <div class="priceSourcing commodity-price-sourcing">
    <PageTitle :goBack="false" title="商品供应商寻源" :border="true" />
<!--    <div class="pageTitle level1 isBorder isPadding myFixed">-->
<!--      <div-->
<!--        class="title"-->
<!--        @click="showA"-->
<!--        :style="{-->
<!--          color: isA ? '#c11a20' : '#333333',-->
<!--        }"-->
<!--        >{{ '商品供应商寻源' }}</div-->
<!--      >-->
<!--      <div-->
<!--        class="title"-->
<!--        :style="{-->
<!--          color: isB ? '#c11a20' : '#333333',-->
<!--        }"-->
<!--        style="margin-left: 50px"-->
<!--        @click="showB"-->
<!--        >{{ '内部采购价格库' }}</div-->
<!--      >-->
<!--    </div>-->
    <div v-show="isA">
      <div class="myCardCss search-query-condition">
        <a-form :model="searchQueryCondition">
          <a-form-item label="关键字" class="keyword-item-box">
            <a-input
              v-model:value="searchQueryCondition.keyword"
              placeholder="请输入商品关键字查询"
            />
            <a-checkbox v-model:checked="searchQueryCondition.isGlobalSearch">全局搜索</a-checkbox>
          </a-form-item>
          <!-- 商品分类 无限下钻 -->
          <!-- 二维数组类型 -->
          <template
            v-for="(categoryChild, index) of searchQueryCondition.categoryList"
            :key="index"
          >
            <a-form-item label="商品分类" v-if="Array.isArray(categoryChild[0])" />
            <!-- 普通类型 -->
            <a-form-item label="商品分类" v-else-if="!Array.isArray(categoryChild[0])">
              <a-checkbox-group
                v-model:value="searchQueryCondition.categoryListIds[index]"
                @change="(value: Array<any>) => categorySelectChange(value, index)"
              >
                <a-checkbox
                  v-for="(item, childIndex) of categoryChild"
                  :value="(item as GetGoodsCategoryResponseInter).id"
                  :key="(item as GetGoodsCategoryResponseInter).id"
                  >{{ (item as GetGoodsCategoryResponseInter).name }}</a-checkbox
                >
              </a-checkbox-group>
            </a-form-item>
          </template>
          <div class="search-btn-container">
            <a-button type="primary" danger class="search-btn" @click="searchbtn">查询</a-button>
            <a-button class="reset-btn" @click="resetSearchCondition">重置</a-button>
          </div>
        </a-form>
      </div>
      <!-- 商品列表 -->
      <div class="myCardCss" style="width: 100%; margin-top: 8px">
        <a-table
          :dataSource="dataSource"
          :columns="columns"
          :pagination="false"
          :loading="searchQueryCondition.tableLoading"
        >
          <template #jj="{ record }">
            <div class="current-average-price">
              <span>{{ parseFloat(record.avgPrice) ? `￥${record.avgPrice}元` : '-' }}</span>
              <span
                class="price-range"
                v-if="parseFloat(record.tbsq)"
                :class="[parseFloat(record.tbsq) < 0 ? 'lower-range' : 'rise-range']"
              >
                {{ parseFloat(record.tbsq) > 0 ? `（+${record.tbsq}）` : `（${record.tbsq}）` }}
              </span>
            </div>
          </template>
          <template #operation="{ record }">
            <a @click="openDetails(record.goodsCode, record.goodsName)" style="color: #1473dc">详情</a>
          </template>
        </a-table>
        <!-- 分页 -->
        <div class="pagination-container">
          <!-- 共有多少条 -->
          <div class="total-container"
            >共 <span>{{ searchQueryCondition.total }}</span> 条</div
          >
          <a-pagination
            v-model:current="searchQueryCondition.pageNum"
            :total="searchQueryCondition.total"
            :defaultPageSize="20"
            show-less-items
            :hideOnSinglePage="true"
            :showSizeChanger="false"
            @change="currentPageChange"
          />
        </div>
      </div>
    </div>
    <div v-show="isB">
      <PriceLib />
    </div>
  </div>
</template>
<script lang="ts" setup>
  import { ref, onBeforeMount, nextTick, watch } from 'vue';
  import { useRoute, useRouter } from 'vue-router';
  import PageTitle from '/@/components/PageTitle/index.vue';
  import { getGoodsCategoryApi, getGoodsListByCategoryApi } from '/@/api/sourcingBigData';
  import { cloneDeep } from 'lodash-es';
  import { getMenuPermission } from '/@/api/checkToken';
  import type {
    GetGoodsCategoryResponseList,
    GetGoodsCategoryResponseInter,
  } from '/#/viewTypes/sourcingBigData';
  import PriceLib from '../priceLibrary/index.vue';
  const routes = useRoute();
  const router = useRouter();

  onBeforeMount(() => {
    init();
    getMenuList();
  });

  let isA = ref(true);
  let isB = ref(false);

  const showA = () => {
    isA.value = true;
    isB.value = false;
  };
  const showB = () => {
    isB.value = true;
    isA.value = false;
  };

  const _defaultTopCategory = [
    {
      name: '常用商品',
      id: 0,
      parentId: null,
    },
    {
      name: '大宗商品',
      id: 1,
      parentId: null,
    },
    {
      name: '工业品',
      id: 2,
      parentId: null,
    },
    {
      name: '办公用品',
      id: 3,
      parentId: null,
    },
  ];

  /**
   * 常用商品 二级分类默认
   */
  const _centerCateGoryDefault = [
    {
      id: 80810,
      name: '变压器',
      paternity: true,
      parentId: 0,
      goodsType: 2,
    },
    {
      id: 85171,
      name: '电缆',
      paternity: true,
      parentId: 0,
      goodsType: 2,
    },
    {
      id: 80904,
      name: '阀门',
      paternity: true,
      parentId: 0,
      goodsType: 2,
    },
    {
      id: 4,
      name: '开关柜',
      paternity: false,
      parentId: 0,
      goodsType: 2,
    },
    {
      id: 96191,
      name: '电压互感器',
      paternity: true,
      parentId: 0,
      goodsType: 2,
    },
    {
      id: 81110,
      name: '电流互感器',
      paternity: true,
      parentId: 0,
      goodsType: 2,
    },
    {
      id: 80877,
      name: '液压工具',
      paternity: true,
      parentId: 0,
      goodsType: 2,
    },
    {
      id: 103365,
      name: '光伏组件',
      paternity: true,
      parentId: 0,
      goodsType: 1,
    },
    {
      id: 3,
      name: '水轮发电机',
      paternity: false,
      parentId: 0,
      goodsType: 2,
    },
  ];

  function getMenuList(){
    getMenuPermission(localStorage.getItem('userId')).then((res) => {
      localStorage.setItem('menuPermissionList', res.menuPermission);
      // window.location.reload()
    }).catch(() => {});
  }

  /**
   * 初始化
   */
  async function init() {
    try {
      const { query } = routes;
      // 路由携带了keyword参数
      if (query.keyword) {
        searchQueryCondition.value['defaultKeyWord'] = query.keyword as string;
      }
      const params = createSearchCondition();
      searchQueryCondition.value.categoryList = [
        cloneDeep(_defaultTopCategory),
        cloneDeep(_centerCateGoryDefault),
      ];
      searchQueryCondition.value.categoryListIds = ['', ''];
      await getGoodsListByCategory(params);
    } catch (error) {
      console.log(error);
    }
  }

  type categoryListType =
    | Array<GetGoodsCategoryResponseList>
    | Array<Array<GetGoodsCategoryResponseList>>;

  interface SearchConditionInter {
    isInit: boolean;
    isGlobalSearch: boolean;
    categoryList: categoryListType;
    categoryListIds: Array<any>;
    categoryId: string | number;
    keyword: string;
    defaultKeyWord: string;
    pageNum: number;
    pageSize: number;
    total: number;
    tableLoading: boolean;
    [key: string]: any;
  }
  const _searchQueryCondition: SearchConditionInter = {
    // 是否是第一次加载
    isInit: true,
    // 是否是全局搜索 默认 true
    isGlobalSearch: true,
    // 无限下钻map
    categoryList: [],
    // 无限下钻map id
    categoryListIds: [],
    // 选中的商品 id 默认阀门id
    categoryId: '',
    // 查询关键词
    keyword: '',
    // 首次进来 默认查询 阀门
    defaultKeyWord: '',
    // 分页查询条件
    pageNum: 1,
    pageSize: 20,
    total: 0,
    tableLoading: false,
  };

  // 查询条件
  const searchQueryCondition = ref(cloneDeep(_searchQueryCondition));

  /**
   * 重置查询条件
   */
  async function resetSearchCondition() {
    searchQueryCondition.value = cloneDeep(_searchQueryCondition);
    await init();
  }

  /**
   * 创建查询条件
   */
  function createSearchCondition() {
    const params = cloneDeep(searchQueryCondition.value) as Partial<SearchConditionInter>;
    const searchQuery = {
      pageNum: params.pageNum,
      pageSize: params.pageSize,
    };
    // 生命周期首次加载 以url 传递的keyword为准
    if (params.isInit) {
      // 查看是否有url传递的keyword 有 默认url  没有则默认隐藏查询 常用商品下的阀门
      const urlKeyword = params.defaultKeyWord;
      if (urlKeyword) {
        searchQuery['keyword'] = urlKeyword;
      } else {
        searchQuery['keyword'] = '阀门';
      }
    } else {
      /**
       * 非首次加载 查看是否是 全局查询  全局 和 选中类别 两个条件互斥
       * 全局查询 查看是否有关键词 有关键词查询关键词 没有关键词查询 阀门 只带keyword 不带 类别id
       * 非全局 查看是否带有关键词 有关键词 查询类别id 以及输入的关键词,没有关键词 查询类别id 以及对应的类别名称
       * 非全局类别id 需要判断是否是 不关联类型 不关联则不查询类别id  只查询keyword
       */
      const isGlobal = params.isGlobalSearch;
      const keyword = params.keyword;
      if (isGlobal) {
        searchQuery['keyword'] = keyword
          ? (searchQuery['keyword'] = keyword)
          : (searchQuery['keyword'] = '阀门');
      } else {
        const ids = params.categoryListIds as Array<any>;
        const categoryList = params.categoryList as categoryListType;
        // 最后一位下标
        let lastIndex = ids.length - 1;
        // 最后一级类别所选id
        let lastId: any = null;
        // 最后一级类别
        let lastArray: GetGoodsCategoryResponseList | Array<GetGoodsCategoryResponseList> = [];
        if (ids[lastIndex] instanceof Array) {
          const lastLen = ids[lastIndex].length;
          lastIndex = lastLen ? lastIndex : lastIndex - 1;
          const hasId = ids[lastIndex] && ids[lastIndex]?.length ? true : false;
          if (hasId) {
            lastId = ids[lastIndex];
            lastArray = categoryList[lastIndex];
          }
        }
        const lastTemp = getValueLevelData(lastArray, lastId);
        if (lastTemp) {
          keyword ? (searchQuery['keyword'] = keyword) : (searchQuery['keyword'] = lastTemp.name);
          lastTemp.paternity === false || (!lastTemp.parentId && lastTemp.parentId != '0')
            ? null
            : (searchQuery['categoryId'] = lastTemp.id);
        }
      }
    }
    return searchQuery;
  }

  /**
   * 根据id获取对应商品名称
   * @param id
   */
  function getCategoryName(tree: any, id: number | string) {
    if (tree instanceof Array) {
    } else if (Object.prototype.toString.call(tree) == '[object Object]') {
    }

    return null;
  }

  function searchbtn() {
    searchQueryCondition.value['pageNum'] = 1;
    searchQueryCondition.value['pageSize'] = 20;
    const query = createSearchCondition();
    getGoodsListByCategory(query);
  }

  /**
   * 页码改变
   */
  function currentPageChange(page: number, pageSize: number) {
    searchQueryCondition.value['pageNum'] = page;
    const query = createSearchCondition();
    getGoodsListByCategory(query);
  }

  // 监听全局搜索
  watch(
    () => searchQueryCondition.value.isGlobalSearch,
    (newVal) => {
      if (newVal) {
        // 选中全局 重置搜索状态
        resetGlobalSearchStatus();
      } else if (!checkCategorySelectValue()) {
        searchQueryCondition.value.isGlobalSearch = true;
      }
    },
  );

  /**
   * 重置全局搜索状态
   */
  function resetGlobalSearchStatus() {
    searchQueryCondition.value.categoryListIds = [];
    searchQueryCondition.value.categoryId = '';
  }

  /**
   * 选中商品类别触发事件
   * @param value
   * @param index
   */
  async function categorySelectChange(value: Array<any>, parentIndex: number) {
    // 每个分类大于一个时 选中最后一次选中的分类
    if (value.length > 1) {
      const len = searchQueryCondition.value.categoryListIds[parentIndex].length;
      searchQueryCondition.value.categoryListIds[parentIndex] = [
        searchQueryCondition.value.categoryListIds[parentIndex][len - 1],
      ];
    } else if (!value.length) {
      // 全取消情况 根据index 重置id 以及 下级
      resetRelationShip(parentIndex);
    }
    // 检查是否存在value
    const hasValue = checkCategorySelectValue();
    // 选中特定类别 全局搜索取消勾选
    if (hasValue) {
      searchQueryCondition.value.isGlobalSearch = false;
    }

    // 获取层级信息
    const listData = searchQueryCondition.value.categoryList[parentIndex];
    const selectValue = searchQueryCondition.value.categoryListIds[parentIndex][0];

    const result = getValueLevelData(listData, selectValue);
    // 有结果
    if (result) {
      // 如果勾选分类为常用商品下的二级分类
      if (parentIndex == 1) {
        const parent = (
          searchQueryCondition.value.categoryList[0] as GetGoodsCategoryResponseList
        ).find((item) => item.id === result.parentId);
        if (parent && parent?.name == '常用商品') {
          searchQueryCondition.value.categoryListIds[0] = [result.parentId];
        }
      }
      await getDeepData(result, parentIndex);
    }
  }

  /**
   * 重置层级关系
   */
  function resetRelationShip(index: number) {
    const temp = cloneDeep(searchQueryCondition.value.categoryList);
    const ids = cloneDeep(searchQueryCondition.value.categoryListIds);
    searchQueryCondition.value.categoryList = temp.splice(0, index + 1);
    searchQueryCondition.value.categoryListIds = ids.splice(0, index + 1);
    if (!checkCategorySelectValue()) {
      searchQueryCondition.value.isGlobalSearch = true;
    }
  }

  /**
   * 获取深层数据信息
   */
  async function getDeepData(result: GetGoodsCategoryResponseInter, index: number) {
    try {
      const _paternity = result.paternity;
      const lastIndex = index + 1;
      const _tempData = cloneDeep(searchQueryCondition.value.categoryList);
      const ids = cloneDeep(searchQueryCondition.value.categoryListIds).splice(0, lastIndex);
      const current = _tempData.splice(0, lastIndex);
      // 没有上下级关系
      if (_paternity === false) {
        searchQueryCondition.value.categoryList = [...current] as any;
      } else {
        const path = createGoodsPath(result, searchQueryCondition.value.categoryListIds, index);
        if (path) {
          const searachResult = await getGoodsCategory(path as string);
          if (searachResult instanceof Array) {
            searchQueryCondition.value.categoryList = searachResult.length
              ? ([...current, searachResult] as any)
              : [...current];
          }
        } else {
          searchQueryCondition.value.categoryList = [
            cloneDeep(_defaultTopCategory),
            cloneDeep(_centerCateGoryDefault),
          ];
        }
        // 重置id
        searchQueryCondition.value.categoryListIds = ids.splice(0, index + 1);
      }
    } catch (error) {
      console.log(error);
    }
  }

  /**
   * 创建商品路径
   * @param path
   * @param pathArray
   * @returns
   *
   */
  function createGoodsPath(
    path: GetGoodsCategoryResponseInter,
    pathArray: Array<any>,
    index: number | string,
  ) {
    if (pathArray.length) {
      const parentId = path.parentId || path.parentId == '0' ? true : false;
      const id = searchQueryCondition.value.categoryListIds[0][0];
      // 查看是否是常用商品
      const isNormal = id == '0' ? true : false;
      if (parentId) {
        if (isNormal) {
          return `/${path.goodsType || 2}/${path.id}`;
        } else {
          return `/${id}/${path.id}`;
        }
      } else if (index == '0') {
        // 第一层级 常用商品
        if (isNormal) {
          return false;
        } else {
          return `/${path.id}`;
        }
      }
    }
  }

  /**
   * getValueLevelData 函数入参data类型
   */
  type GetValueLevelDataType =
    | Array<Array<GetGoodsCategoryResponseList>>
    | GetGoodsCategoryResponseList
    | Array<GetGoodsCategoryResponseList>
    | GetGoodsCategoryResponseInter;
  /**
   * 获取选中类别层级信息
   *
   */
  function getValueLevelData(
    data: GetValueLevelDataType,
    id: number | string,
  ): GetGoodsCategoryResponseInter | null {
    if (!id && id != '0') return null;
    if (data instanceof Array) {
      const len = data.length;
      for (let index = 0; index < len; index++) {
        const item = data[index];
        const result = getValueLevelData(item, id);
        if (result) return result as GetGoodsCategoryResponseInter;
      }
    } else if (Object.prototype.toString.call(data) == '[object Object]') {
      if (data.id == id && (id || id == '0')) return data as GetGoodsCategoryResponseInter;
    }
    return null;
  }

  /**
   * 检查选中类别
   */
  function checkCategorySelectValue() {
    return searchQueryCondition.value.categoryListIds.some((item) => {
      if (item instanceof Array) {
        return item.length ? true : false;
      } else if (item || item == '0') {
        return true;
      }
      return false;
    });
  }

  /**
   * 获取分类子级
   * @param path
   */
  async function getGoodsCategory(path: string) {
    try {
      const result = await getGoodsCategoryApi(path);
      if (result instanceof Array) {
        return result;
      }
    } catch (error) {}
  }

  /**
   * 获取商品列表
   * @param params
   */
  async function getGoodsListByCategory(params: any) {
    try {
      searchQueryCondition.value['tableLoading'] = true;
      const resultList = await getGoodsListByCategoryApi(params);
      if (resultList) {
        dataSource.value = resultList.list ? resultList.list : [];
        dataSource.value = dataSource.value.map(item => {
          if ( !item.goodsBrand ) {
            item.goodsBrand = '-'
          }
          return item
        })
        searchQueryCondition.value['total'] = resultList.total ? resultList.total : 0;
        searchQueryCondition.value['pageNum'] = resultList.currentPage ? resultList.currentPage : 1;
        await scrollToTop();
        // 首次加载完 重置init 首次加载状态
        searchQueryCondition.value.isInit ? (searchQueryCondition.value.isInit = false) : null;
      }
    } catch (error) {
    } finally {
      searchQueryCondition.value['tableLoading'] = false;
    }
  }

  async function scrollToTop() {
    await nextTick();
    const container = document.body;
    if (container) {
      container.scrollTo({
        top: 0,
        behavior: 'smooth',
      });
    }
  }

  let dataSource = ref();

  let columns = ref([
    {
      title: '商品信息',
      dataIndex: 'goodsName',
      key: 'goodsName',
      align: 'left',
      ellipsis: true,
      slots: { customRender: 'goodsName' },
    },
    {
      title: '品牌',
      dataIndex: 'goodsBrand',
      key: 'goodsBrand',
      align: 'left',
      ellipsis: true,
      width: '200px',
    },
    {
      title: '类别',
      dataIndex: 'category',
      key: 'category',
      align: 'left',
      ellipsis: true,
      width: '150px',
    },
    {
      title: '当前均价（较上期）',
      dataIndex: 'jj',
      key: 'jj',
      width: '230px',
      slots: { customRender: 'jj' },
    },
    {
      title: '单位',
      dataIndex: 'unit',
      key: 'unit',
      align: 'left',
      width: '70px',
    },
    // {
    //   title: '价格趋势',
    //   dataIndex: 'address',
    //   key: 'address',
    //   align: 'center',
    // },
    // {
    //   title: '供应商数量',
    //   dataIndex: 'num',
    //   key: 'num',
    //   align: 'center',
    // },
    {
      title: '操作',
      dataIndex: 'operation',
      key: 'operation',
      slots: { customRender: 'operation' },
      align: 'center',
      width: '80px',
    },
  ]);

  /**
   * 跳转到详情
   * @param {string | number} id 详情id
   */
  function openDetails(id: string | number, name: string) {
    localStorage.setItem('goodsName', name)
    if (!id) return;
    router.push({
      path: `/sourcingBigData/productDetail/${id}`,
    });
  }
</script>

<style lang="less" scoped>
  .commodity-price-sourcing {
    :deep(.search-query-condition) {
      padding: 16px;

      .ant-form-item {
        .ant-form-item-label {
          label {
            line-height: 22px;
            height: 22px;

            &::after {
              display: none;
            }
          }
        }

        .ant-form-item-control {
          margin-left: 20px;

          .ant-form-item-control-input {
            min-height: 22px;
            padding: 0px !important;

            .ant-checkbox-wrapper {
              margin-right: 20px;
              margin-bottom: 15px;
              &:first-child {
                margin-left: 0px !important;
              }

              & + .ant-checkbox-wrapper {
                margin-left: 0px !important;
              }

              .ant-checkbox-inner,
              .ant-checkbox-input {
                width: 14px;
                height: 14px;
              }

              .ant-checkbox-checked {
                .ant-checkbox-inner {
                  &::after {
                    width: 5px;
                    height: 8px;
                  }
                }
              }
            }
          }
        }

        &.keyword-item-box {
          align-items: center;

          .ant-checkbox-wrapper {
            margin-left: 16px;
            margin-right: 0px;
          }

          .ant-input {
            width: 280px;
          }
        }
      }

      // 查询条件按钮
      .search-btn-container {
        display: flex;
        // padding-left: 76px;
        padding-top: 8px;
        box-sizing: border-box;
        padding-left: 76px;

        .search-btn {
          border-radius: 4px;
          color: #fff;
          border: none;
          margin-right: 12px;
        }

        .reset-btn {
          border-radius: 4px;
          color: #606266;
          border: 1px solid #dcdfe6;

          &:hover {
            color: #c11a20;
            border-color: #c11a20;
          }
        }
      }
    }

    // 列表
    :deep(.ant-table) {
      .current-average-price {
        display: flex;
        align-items: center;
        justify-content: left;

        .lower-range {
          color: #16af44;
        }

        .rise-range {
          color: #c11a20;
        }
      }
    }

    :deep(.pagination-container) {
      display: flex;
      align-items: center;
      justify-content: flex-end;
      margin-top: 16px;

      .ant-pagination {
        margin-left: 16px;

        .ant-pagination-item {
          border: unset !important;
          height: 32px !important;
          line-height: 32px !important;

          &.ant-pagination-item-active {
            background-color: #fff !important;

            a {
              color: #c11a20 !important;
            }
          }
        }

        .ant-pagination-next,
        .ant-pagination-prev {
          height: 32px !important;
          line-height: 32px !important;
          border: unset !important;

          .ant-pagination-item-link {
            border: unset !important;
            display: flex;
            align-items: center;
            justify-content: center;
          }
        }
      }

      .total-container {
        color: #606266;
        font-size: 14px;

        & > span {
          color: #c11a20;
        }
      }
    }
  }

  .pageTitle {
    width: 100%;
    height: 48px;
    display: flex;
    background: #ffffff;
    user-select: none;

    .back-item {
      margin-right: 16px;
      cursor: pointer;

      .back-img {
        margin-right: 10px;
        display: inline;
        line-height: 48px;
      }

      .goBack {
        font-size: 14px;
        color: #303133;
        line-height: 48px;
      }
    }

    .title-tag {
      width: 2px;
      height: 14px;
      background: #c11a20;
      margin-right: 8px;
      display: inline;
      margin-top: 18px;
    }

    .title {
      font-weight: bold;
      line-height: 48px;
      color: #303133;
      cursor: pointer;

      &:hover {
        color: #c11a20;
      }
    }
  }

  .isBorder {
    border-bottom: 1px solid #dcdfe6;
  }

  .isPadding {
    padding: 0 16px;
  }

  .level1 {
    font-size: 16px;
  }

  .level2 {
    font-size: 14px;
  }
  .myFixed {
    position: fixed;
    z-index: 10;
    width: calc(100% - 258px);
    background: #ffffff;
  }
  .search-query-condition {
    padding-top: 20px !important;
  }
  .collaborationLedger {
    padding-top: 48px !important;
  }
</style>
